#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <wait.h>

#define NUM 3

typedef void (*task)(void);

pid_t fork_task(task t)
{
    pid_t ret = fork();
    if (ret == 0)
    {
        t();
        exit(0);
    }
    else if (ret > 0)
        return ret;
    else
        perror("fork error");
}

void task1()
{
    for (int i = 0; i < 5; ++i)
    {
        printf("绘制界面 pid = %d\n", getpid());
        sleep(1);
    }
}

void task2()
{
    for (int i = 0; i < 4; ++i)
    {
        printf("检查环境 pid = %d\n", getpid());
        sleep(1);
    }
}

void task3()
{
    for (int i = 0; i < 3; ++i)
    {
        printf("等待响应 pid: %d\n", getpid());
        sleep(1);
    }
}

int main()
{
    task task_queue[NUM] = { task1, task2, task3 };
    pid_t id_arr[NUM];
    for (int i = 0; i < NUM; ++i)
        id_arr[i] = fork_task(task_queue[i]);
    
    while (1)
    {
        int state = 0;
        pid_t ret = waitpid(-1, &state, WNOHANG);
        if (ret < 0)
            printf("wait error\n");
        else if (ret > 0)
        {
            for (int i = 0; i < NUM; ++i)
            {
                if (ret == id_arr[i])
                    id_arr[i] = fork_task(task_queue[i]);
            }
        }
        else
            printf("父进程执行逻辑 pid: %d\n", getpid());
        sleep(1);
    }
    return 0;
}
